package visualisation;

import java.awt.BorderLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import engine.AlternateStateThreadPoolExecutor;
import engine.SchedulerControlComponent;
import fragment.Fragment;

public class MainFrame extends JFrame{
	
	private JButton stepButton;

	public MainFrame(Vector<Fragment> fragList)
			throws HeadlessException {
		super("ADELFE");
		
		JSplitPane splitPane= new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, CompositionView.visualise("name", fragList), ProcessView.visualise("name", fragList));
		splitPane.setResizeWeight(0.5);
			
		stepButton = new JButton("next step");
		stepButton.setEnabled(false);
		stepButton.addActionListener(new stepActionListener(stepButton));
	
		JPanel MainPanel=new JPanel();
		MainPanel.setLayout(new BorderLayout());
		MainPanel.add(splitPane, BorderLayout.CENTER);
		MainPanel.add(new SchedulerControlComponent(engine.AlternateStateThreadPoolExecutor.processExe), BorderLayout.SOUTH);
	
		

        this.setContentPane(MainPanel);
        this.pack();
        this.setVisible(true);
        		         
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	class stepActionListener implements ActionListener{
		
		protected JButton b;
		
		public stepActionListener(JButton b){
			this.b=b;
		}
		
		@Override
		public void actionPerformed(ActionEvent e) {
			if(b.isEnabled()){
				AlternateStateThreadPoolExecutor.processExe.nextStep();
			}			
		}
		
	}
	
	class sliderListener implements ChangeListener{

		@Override
		public void stateChanged(ChangeEvent e)  {
			
			 JSlider source = (JSlider)e.getSource();
			    if (!source.getValueIsAdjusting()) {
			        int state = source.getValue();
			        switch(state){
			        	case 1:
			        		AlternateStateThreadPoolExecutor.processExe.pause();
			        		MainFrame.this.stepButton.setEnabled(false);
			        		break;
			        	case 2:
			        		AlternateStateThreadPoolExecutor.processExe.pause();
			        		MainFrame.this.stepButton.setEnabled(true);
			        		break;
			        	case 3:
			        		AlternateStateThreadPoolExecutor.processExe.goSlow();
			        		MainFrame.this.stepButton.setEnabled(false);
			        		break;
			        	case 4:
			        		AlternateStateThreadPoolExecutor.processExe.goFast();
			        		MainFrame.this.stepButton.setEnabled(false);
			        		break;
			        }
			    }

		
		}

	}
	
	
}
